import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { login } from '../services/user';
import { setAuthority, getUser } from '../utils/authority';
import { reloadAuthorized } from '../utils/Authorized';
import { getPageQuery } from '../utils/utils';

export default {
  namespace: 'login',

  state: {
    status: !!getUser(),
    data: getUser() || {}
  },

  effects: {
    *login({ payload }, { call, put }) {
      const {data: {admin}} = yield call(login, payload); // 登陆用户信息
      admin.authority = ['isLogin']
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: true,
          data: admin // 用户信息
        },
      });
      reloadAuthorized(); // 重新设置路由权限
      const urlParams = new URL(window.location.href);
      const params = getPageQuery();
      let { redirect } = params;
      if (redirect) {
        const redirectUrlParams = new URL(redirect);
        if (redirectUrlParams.origin === urlParams.origin) {
          redirect = redirect.substr(urlParams.origin.length);
          if (redirect.startsWith('/#')) {
            redirect = redirect.substr(2);
          }
        } else {
          window.location.href = redirect;
          return;
        }
      }
      yield put(routerRedux.replace(redirect || '/'));
    },
    *logout(_, { put }) {
      localStorage.clear() // 登出清空缓存
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          data: '', // 清空用户信息
        },
      });
      reloadAuthorized();
      yield put(
        routerRedux.push({
          pathname: '/user/login',
          search: stringify({
            redirect: '',
          }),
        })
      );
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      const {data, status} = payload
      setAuthority(data); // 本地缓存用户信息
      return {
        ...state,
        data,
        status
      };
    },
  },
};
